package com.peter.smv.utils

import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.Window
import java.io.File

class ScreenShot(val context: Context) {

    fun screenShot(window: Window, callBack: (bitMap: Bitmap) -> Unit) {
        val dcView = window.decorView
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val bitMap = Bitmap.createBitmap((dcView.width * 0.5f).toInt(), (dcView.height * 0.5f).toInt(), Bitmap.Config.ARGB_8888)
            PixelCopy.request(window, bitMap, {
                callBack.invoke(bitMap)
            }, Handler(Looper.getMainLooper()))
        } else {
            dcView.isDrawingCacheEnabled = true
            val bitMap = dcView.drawingCache
            callBack.invoke(bitMap)
        }
    }

    fun saveBitMapToData(bitMap: Bitmap, fileName: String, callBack: (saveFile: File) -> Unit) {
        //获取文件缓存路径
        Thread {
            val file = File(context.cacheDir.absolutePath + File.separator + "screenShort")
            if (!file.exists()) {
                file.mkdirs()
            }
            val saveFile = File(file.absolutePath + File.separator + "${fileName}.jpg")
            val fos = saveFile.outputStream()
            bitMap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
            bitMap.recycle()
            callBack.invoke(saveFile)
        }.start()
    }

    fun screenShotAndSave(window: Window, fileName: String, callBack: (saveFile: File) -> Unit) {
        screenShot(window) {
            saveBitMapToData(it, fileName, callBack)
        }
    }

}